<template>
    <div :style="dynamicStyles">
        <el-card class="box-card-btn">
            <el-button type="primary" @click="onSubmit">导出</el-button>
        </el-card>
        <el-card class="box-card">
            <el-table id="table" :data="tableData" :height="height" style="width: 100%" :summary-method="getSummaries" :show-summary="showSummary">
                <el-table-column v-for="(item, index) in columns" :key="index" :prop="item.prop" :label="item.label">
                </el-table-column>
            </el-table>

            <el-pagination v-if="propValue.isHavePage" @current-change="handleCurrentChange" :current-page.sync="page.currentPage" :page-size="page.pageSize"
                layout="total, prev, pager, next" :total="total">
            </el-pagination>
        </el-card>
    </div>
</template>

<script>
import OnEvent from '../common/OnEvent'
import { exportToExcel } from '../../utils/Export2Excel'
import { getExecuteQuery } from '../../../../api/table/index'
export default {
    extends: OnEvent,
    props: {
        propValue: {
            type: Object,
            default: () => { },
        },
        request: {
            type: Object,
            default: () => { },
        },
        element: {
            type: Object,
            default: () => { },
        },
    },
    data() {
        return {
            formInline: {},
            showSummary: false,
            cancelRequest: null,
            tableData: [],
            columns: [],
            total: 0,
            height: 150,
            page: {
                currentPage: 1,
                pageSize: 10
            },
            showSummaryType: 0,
            dynamicStyles: {
                width: '0px',
                height: '0px',
                borderRadius: '0px',
                fontSize: "0"
            }
        }
    },
    mounted() {
        // if (this.request) {
        //     this.cancelRequest = request(this.request, this.propValue, 'data')
        // }
        this.tableData = this.propValue.data
        this.columns = this.propValue.columns
        this.generateSql(this.propValue.sql)
        console.log(this.propValue)
        const { width, height } = this.element.style
        this.dynamicStyles.width = width + "px"
        this.dynamicStyles.height = height + 'px'
        this.height = height
        this.showSummaryType = this.propValue.showSummaryType
    },
    watch: {
        'element.style.width': function () {
            const { width, height } = this.element.style
            this.dynamicStyles.width = width + "px"
            this.dynamicStyles.height = height + 'px'
            this.dynamicStyles.borderRadius = this.propValue.border + 'px'
            this.height = this.propValue.height
        },
        'element.style.height': function () {
            const { width, height } = this.element.style
            this.dynamicStyles.width = width + "px"
            this.dynamicStyles.height = height + 'px'
            this.dynamicStyles.borderRadius = this.propValue.border + 'px'
        },
        'propValue.data': function () {
            this.tableData = this.propValue.data
            // console.log(this.tableData)
        },
        'propValue.columns': function () {
            this.columns = this.propValue.columns
            // console.log(this.columns)
        },
        'element.style.height': function () {
            this.height = this.element.style.height -150
            // console.log(this.total)
        },
        'propValue.total': function () {
            this.total = this.propValue.total
            // console.log(this.total)
        },
        'propValue.showSummary': function () {
            this.showSummary = this.propValue.showSummary
        },
        'propValue.isHavePage': function () {
            this.page.currentPage = 1
            this.page.pageSize = 99999
            this.generateSql(this.propValue.sql)
        },
        'propValue.showSummaryType': function () {
            this.showSummaryType = this.propValue.showSummaryType
            this.generateSql()
        }
    },
    beforeDestroy() {
        this.request
    },
    methods: {
        /**
         * 导出
         */
        onSubmit() {
            exportToExcel('#table', '报表导出二');
        },
        download() {
            let dataList = this.$store.state.curComponent.propValue.data
            this.downloadLoading = true
            // console.log(this.$store.state.curComponent.propValue.columns)
            let columns = this.$store.state.curComponent.propValue.columns
            let tHeader = []
            let filterVal = []
            for (let i in columns) {
                tHeader.push(columns[i].label)
                filterVal.push(columns[i].prop)
            }
            import('../../utils/Export2Excel').then(excel => {
                const data = this.formatJson(filterVal, dataList)
                excel.export_json_to_excel({
                    header: tHeader,
                    data,
                    filename: '自己定义'
                })
                this.downloadLoading = false
            })
        },
        formatJson(filterVal, jsonData) {
            return jsonData.map(v => filterVal.map(j => {
                console.log(j)
                if (j === 'createTime') {
                    return parseTime(v[j])
                } else {
                    return v[j]
                }
            }))
        },
        handleCurrentChange(val) {
            this.page.currentPage = val
        },
        /**
         * 生成sql语句
         */
        generateSql(sql) {
            console.log(this.propValue.sql)
            // let field = this.fieldName.toString();
            // let sql = "select " + field + " from " + this.tableName
            if (this.propValue.sql) {
                getExecuteQuery({
                    sql: this.propValue.sql,
                    pageNum: this.page.currentPage,
                    pageSize: this.page.pageSize
                }).then(response => {
                    this.$store.state.curComponent.propValue.data = response.records
                    // this.page.currentPage = response.pageNum
                    this.total = response.total
                    // this.$store.state.curComponent.propValue.sqsl = sql
                });
            }
        },
        getValue(param) {
            console.log(param)
            this.getSummaries(param);
        },
        /**
         * 
         * 求和
         */
        getSummaries(param) {
            if (this.showSummaryType == 0) {
                const { columns, data } = param;
                const sums = [];
                columns.forEach((column, index) => {
                    if (index === 0) {
                        sums[index] = '总和';
                        return;
                    }
                    const values = data.map(item => Number(item[column.property]));
                    if (!values.every(value => isNaN(value))) {
                        sums[index] = values.reduce((prev, curr) => {
                            const value = Number(curr);
                            if (!isNaN(value)) {
                                return prev + curr;
                            } else {
                                return prev;
                            }
                        }, 0);
                        sums[index] += '';
                    } else {
                        sums[index] = 'N/A';
                    }
                });

                return sums;
            } else if (this.showSummaryType == 1) {
                const { columns, data } = param;
                const averages = [];
                columns.forEach((column, index) => {
                    if (index === 0) {
                        averages[index] = '平均数';
                        return;
                    }
                    const values = data.map(item => Number(item[column.property]));
                    const validValues = values.filter(value => !isNaN(value)); // 过滤掉非数字的值

                    if (validValues.length > 0) {
                        const sum = validValues.reduce((prev, curr) => prev + curr, 0);
                        const average = sum / validValues.length;
                        averages[index] = average.toFixed(2); // 保留两位小数
                    } else {
                        averages[index] = 'N/A';
                    }
                });

                return averages;
            } else if (this.showSummaryType == 2) {
                const { columns, data } = param;
                const maxValues = [];
                columns.forEach((column, index) => {
                    if (index === 0) {
                        maxValues[index] = '最大值';
                        return;
                    }
                    const values = data.map(item => Number(item[column.property]));
                    const validValues = values.filter(value => !isNaN(value)); // 过滤掉非数字的值

                    if (validValues.length > 0) {
                        const maxValue = Math.max(...validValues); // 获取最大值
                        maxValues[index] = maxValue;
                    } else {
                        maxValues[index] = 'N/A';
                    }
                });

                return maxValues;
            } else if (this.showSummaryType == 3) {
                const { columns, data } = param;
                const minValues = [];
                columns.forEach((column, index) => {
                    if (index === 0) {
                        minValues[index] = '最小值';
                        return;
                    }
                    const values = data.map(item => Number(item[column.property]));
                    const validValues = values.filter(value => !isNaN(value)); // 过滤掉非数字的值

                    if (validValues.length > 0) {
                        const minValue = Math.min(...validValues); // 获取最小值
                        minValues[index] = minValue;
                    } else {
                        minValues[index] = 'N/A';
                    }
                });

                return minValues;
            }
        },
        /**
         * 平均数
         */
        getAverages() {
            const { columns, data } = param;
            const averages = [];
            columns.forEach((column, index) => {
                if (index === 0) {
                    averages[index] = '平均数';
                    return;
                }
                const values = data.map(item => Number(item[column.property]));
                const validValues = values.filter(value => !isNaN(value)); // 过滤掉非数字的值

                if (validValues.length > 0) {
                    const sum = validValues.reduce((prev, curr) => prev + curr, 0);
                    const average = sum / validValues.length;
                    averages[index] = average.toFixed(2); // 保留两位小数
                } else {
                    averages[index] = 'N/A';
                }
            });

            return averages;
        },
        /**
         * 最大值
         */
        getMaxValues() {
            const { columns, data } = param;
            const maxValues = [];
            columns.forEach((column, index) => {
                if (index === 0) {
                    maxValues[index] = '最大值';
                    return;
                }
                const values = data.map(item => Number(item[column.property]));
                const validValues = values.filter(value => !isNaN(value)); // 过滤掉非数字的值

                if (validValues.length > 0) {
                    const maxValue = Math.max(...validValues); // 获取最大值
                    maxValues[index] = maxValue;
                } else {
                    maxValues[index] = 'N/A';
                }
            });

            return maxValues;
        },

        /**
         * 最小值
         */
        getMinValues() {
            const { columns, data } = param;
            const minValues = [];
            columns.forEach((column, index) => {
                if (index === 0) {
                    minValues[index] = '最小值';
                    return;
                }
                const values = data.map(item => Number(item[column.property]));
                const validValues = values.filter(value => !isNaN(value)); // 过滤掉非数字的值

                if (validValues.length > 0) {
                    const minValue = Math.min(...validValues); // 获取最小值
                    minValues[index] = minValue;
                } else {
                    minValues[index] = 'N/A';
                }
            });

            return minValues;
        }

    }
}
</script>

<style lang="scss" scoped>
.v-table {
    border-collapse: collapse;
    table-layout: fixed;
    word-break: break-all;
    word-wrap: break-word;

    td {
        border: 1px solid #ebeef5;
        height: 40px;
        width: 60px;
        padding: 10px;
    }

    .bold {
        font-weight: bold;
    }

    .stripe {
        background-color: #fafafa;
    }
}

.box-card-btn {
    width: 100%;
    // display: flex;
    text-align: right;
    // justify-items: flex-end;
}
</style>
